<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    function longestCommonPrefix(strs) {
      if (strs.length === 0) return ""
      let prefix = strs[0]
      for (let i = 1; i <strs.length; i++) {
        // indexOf方法用于查找子字符串在字符串中首次出现的位置
        // 如果字符串以prefix开头，则indexOf(prefix)返回0
        // 如果字符串不以prefix开头，则返回-1或其他位置值
        // 在最长公共前缀算法中，我们需要确保每个字符串都以当前prefix开头
        // 所以这里检查indexOf(prefix)是否等于0，不等于0就需要缩短prefix
        console.log(`当前前缀"${prefix}"在"${strs[i]}"中的位置: ${strs[i].indexOf(prefix)}`);
        
        while (strs[i].indexOf(prefix) !== 0) {
          prefix = prefix.substring(0, prefix.length - 1)
          if (prefix.length === 0) return ""
        }
      }
      return prefix
    }
    console.log(longestCommonPrefix(["flower", "flow", "flight"])) // "fl"
    console.log(longestCommonPrefix(["dog", "racecar", "car"])) // ""
    console.log(longestCommonPrefix(["flower", "flower", "flower"])) // "flower"
    console.log(longestCommonPrefix([])) // ""
    console.log(longestCommonPrefix(["a"])) // "a"
    console.log(longestCommonPrefix(["ab", "a"])) // "a"
    

  </script>
</html>
